package org.example.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.component.SmsComponent;
import org.example.config.SmsConfig;
import org.example.constant.RedisKey;
import org.example.enums.BizCodeEnum;
import org.example.enums.SendCodeEnum;
import org.example.service.NotifyService;
import org.example.util.CheckUtil;
import org.example.util.CommonUtil;
import org.example.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {
    /**
     * 十分钟有效
     */
    private static final int CODE_EXPIRED = 60 * 1000 * 10;
    @Autowired
    private SmsComponent smsComponent;
    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {

        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        // 如果不为空，则判断收60秒内重复发送。 格式： 2222_时间戳
        if (StringUtils.isNotBlank(cacheValue)) {
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            long leftTime = CommonUtil.getCurrentTimestamp() - ttl;
            if(leftTime < (1000 * 60)) {
                log.info("重复发送短信验证码，时间间隔: {} 秒", leftTime / 1000);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }

        String code = CommonUtil.getRandomCode(6);
        // 生成拼接好的验证码
        String value = code + "_" + CommonUtil.getCurrentTimestamp();
        redisTemplate.opsForValue().set(cacheKey, value, CODE_EXPIRED, TimeUnit.MILLISECONDS);

        if (CheckUtil.isEmail(to)) {
            // 发送邮箱验证码 TODO
        } else if (CheckUtil.isPhone(to)) {
            // 发送验证码
            smsComponent.send(to, smsConfig.getTemplateId(), code);
        }
        return JsonData.buildSuccess(code);
    }

    /**
     * 验证码校验逻辑
     *
     * @param sendCodeEnum
     * @param to
     * @param code
     * @return
     */
    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if(StringUtils.isNotBlank(cacheValue)) {
            String cacheCode = cacheValue.split("_")[0];
            if(cacheCode.equals(code)) {
                //删除验证码
                redisTemplate.delete(cacheKey);
                return true;
            }
        }
        return false;
    }

//    @Override
//    //@Async("threadPoolTaskExecutor")
//    public void textSendSms() {
////        try {
////            TimeUnit.MILLISECONDS.sleep(200);
////        }catch (InterruptedException e){
////            e.printStackTrace();
////        }
//        ResponseEntity<String> forEntity = restTemplate.getForEntity("https://www.scun.edu.cn/", String.class);
//        String key = forEntity.getBody();
//        log.info(key);
//    }
}
